package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "http://localhost:8081")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    // 模拟数据库
    private final ConcurrentHashMap<Long, User> userMap = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);

    // 用户实体类
    static class User {
        @JsonProperty("id")
        private Long id;

        @JsonProperty("name")
        private String username;

        @JsonProperty("email")
        private String email;

        public User() {}

        public User(Long id, String username, String email) {
            this.id = id;
            this.username = username;
            this.email = email;
        }

        // Getter 和 Setter
        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }

        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }

        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
    }

    // 获取用户列表
    @GetMapping("/get")
    public List<User> getUsers() {
        return new ArrayList<>(userMap.values());
    }

    // 根据用户名搜索用户
    @GetMapping("/search")
    public List<User> searchUsers(@RequestParam("name") String name) {
        return userMap.values().stream()
                .filter(user -> user.getUsername().contains(name))
                .collect(Collectors.toList());
    }

    // 创建用户
    @PostMapping
    public User createUser(@RequestBody User user) {
        long newId = idGenerator.getAndIncrement();
        User newUser = new User(newId, user.getUsername(), user.getEmail());
        userMap.put(newId, newUser);
        logger.info("用户添加成功，当前用户列表: {}", formatUserList(userMap.values()));
        return newUser;
    }

    // 更新用户
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User updatedUser) {
        User user = userMap.get(id);
        if (user != null) {
            user.setUsername(updatedUser.getUsername());
            user.setEmail(updatedUser.getEmail());
            logger.info("用户更新成功，当前用户列表: {}", formatUserList(userMap.values()));
            return user;
        }
        return null;
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userMap.remove(id);
        logger.info("用户删除成功，当前用户列表: {}", formatUserList(userMap.values()));
    }

    // 删除所有用户
    @DeleteMapping
    public void deleteAllUsers() {
        userMap.clear();
        logger.info("所有用户删除成功，当前用户列表: {}", formatUserList(userMap.values()));
    }

    // 格式化方法 - 修复了formatUser方法缺失的问题
    private String formatUserList(Collection<User> users) {
        if (users == null || users.isEmpty()) {
            return "空列表";
        }
        return users.stream()
                .map(user -> String.format("%s<%s>", user.getUsername(), user.getEmail()))
                .collect(Collectors.joining(", "));
    }
}